#include <QtGui>

#include "StringListDemo.h"

StringListDemo::StringListDemo(const QStringList &stringList,
							   QWidget *parent) : QDialog(parent)
{
	model = new QStringListModel(this);
	model->setStringList(stringList);

	listView = new QListView;
	listView->setModel(model);
	listView->setEditTriggers(QAbstractItemView::AnyKeyPressed
		| QAbstractItemView::DoubleClicked);

	btnInsert = new QPushButton(tr("Insert"));
	btnAppend = new QPushButton(tr("Append"));
	btnDel = new QPushButton(tr("Delete"));

	connect(btnInsert, SIGNAL(clicked()), this, SLOT(insert()));
	connect(btnAppend, SIGNAL(clicked()), this, SLOT(append()));
	connect(btnDel, SIGNAL(clicked()), this, SLOT(del()));

	buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok
									 | QDialogButtonBox::Cancel);
	connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
	connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));

	QHBoxLayout *btnLayout = new QHBoxLayout;
	btnLayout->addWidget(btnInsert);
	btnLayout->addWidget(btnAppend);
	btnLayout->addWidget(btnDel);

	QVBoxLayout *mainLayout = new QVBoxLayout;
	mainLayout->addWidget(listView);
	mainLayout->addLayout(btnLayout);
	mainLayout->addWidget(buttonBox);
	setLayout(mainLayout);

	setWindowTitle(tr("String List Demo"));
}

void StringListDemo::done(int result)
{
	id = -1;
	if (result == QDialog::Accepted) {
		id = listView->currentIndex().row();
	}
	QDialog::done(result);
}

void StringListDemo::insertRow(int row)
{
	QModelIndex index = model->index(row);
	model->insertRows(row, 1);
	model->setData(index, "EMPTY");

	listView->setCurrentIndex(index);
	listView->edit(index);
}

void StringListDemo::insert()
{
	int row = listView->currentIndex().row();
	insertRow(row);
}

void StringListDemo::append()
{
	int row = listView->currentIndex().row();
	insertRow(row + 1);
}

void StringListDemo::del()
{
	model->removeRows(listView->currentIndex().row(), 1);
}
